% Brief Introduction:
% This function evaluates the spline given its polynomial coefficients.
% Usage:
%   PolyValue   =   Spline1dPPEval(breaks,k,PCoef,x)
% Inputs:
%   breaks      :   Vector of break points, accendingly sorted
%   k           :   Polynomial order of the spline
%   PCoef       :   The Polynomial representation coefficient matrix, 
%                   its dimension is (#breaks-1) x (k+1)
% OUTPUTS
%   PolyValue   :   Value of the spline at x
%
% Author:       Xing Guo, University of Michigan, xingguo@umich.edu
% Version:      Nov 28, 2017               
% USES: PCoefDer 

function PolyValue=Spline1dPPEval(breaks,PCoef_0,x,order,MultiBreakFlag)

% Lookup the index for the intervals where each evaluation point sits 
if nargin==5 && MultiBreakFlag==1
    UniBreaks   =   unique(breaks);
else
    UniBreaks   =   breaks;
end
ind         =   lookup(UniBreaks,x,3);
PolyValue   =   cell(size(order));
% x-break_interval_left_end
PolyTerm    =   x-UniBreaks(ind);

for i=1:length(order)
    PCoef       =   PCoefDer(PCoef_0,order(i));
    % Polynomial coefficients for each x
    PolyCoef    =   PCoef(ind,:);
    % Horner's evaluation 
    Value_temp  =   zeros(size(PolyCoef,1),1);
    for j=1:size(PolyCoef,2)
        Value_temp      =   PolyCoef(:,j)+bsxfun(@times,Value_temp,PolyTerm);
    end
    PolyValue{i}    =   Value_temp;
end

if length(order)==1
    PolyValue       =   PolyValue{1};
end
